#!/usr/bin/env python
# -*- coding:utf-8 -*-
import MySQLdb
import time
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

def get_data(item):
    sql='select ip,%s from data ORDER BY DATE DESC limit 1;'%item
    cur.execute(sql)
    ret=cur.fetchall()[0]
    cur.close()
    conn.close()
    return ret

def send_email(content):
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['From'] = formataddr(["jinxl",'jinxl@126.com'])
    msg['To'] = formataddr(["jxl",'42136639@qq.com'])
    msg['Subject'] = "warning"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("jinxl@126.com", "123456")
    server.sendmail('jinxl@126.com', ['42136639@qq.com',], msg.as_string())
    server.quit()

if __name__ == '__main__':
    while True:
        for item in ('cpu','procnum'):
            conn=MySQLdb.connect(host='192.168.136.8',user='root',passwd='123456',db='monitor')
            cur=conn.cursor()
            ip,item_data=get_data(item)
            if item == 'cpu':
                if item_data < 0.1:
                    content="%s %s load 1 minite is :%s"%(ip,item,item_data)
                    print content
                else:
                    content="%s\033[31;1m %s load too high, the value is: %s\033[0m"%(ip,item,item_data)
                    print content
                    send_email(content)
            elif item == 'procnum':
                if item_data <300:
                    content="%s %s process number ok! the value is :%s"%(ip,item,item_data)
                    print content
                else:
                    content="%s\033[31;1m %s process number too high! the value is :%s\033[0m"%(ip,item,item_data)
                    print content
                    send_email(content)
        time.sleep(10)